import {createRouter, createWebHashHistory, createWebHistory} from "vue-router";

import {toStore } from "../stores/counter.js";
import {verifyToken} from "../request/system/RouterApi.js";


const routes = [
  {
    path: "/",
    name:"login",
    component: import("../view/LoginView.vue")
  },
  {
    path: "/register",
    name:"register",
    component: import("../view/RegisterView.vue")
  },
  {
    name: "admin",
    path: "/admin",
    component: import("../view/AdminView.vue"),
    children:[{
      path: "/admin/CodeBuild",
        component: import("../view/admin/system/CodeBuild.vue")
      }
    ]
  }

]
export const router = createRouter({
  history: createWebHistory(),
  routes: routes,
  mode: 'history' // 去掉url中的#

})
router.beforeEach(async (to, from) => {
  // 前端拦截器

  const store = toStore()

  if (to.fullPath === "/admin") {
    if (store.token === "") {
      return {path: "/"}
    }
    let power = true;
    await verifyToken(store.token).then((response) => {
      power = response.state == "200";
    })
    if (!power) {
      return {path: "/"}
    }
  } else if (to.fullPath.indexOf("admin") !== -1 && router.resolve(to.fullPath).matched.length === 0) {
    return {path: "/admin"}
  } else if (router.resolve(to.fullPath).matched.length === 0) {
    return {path: "/404"}
  }
  return true
})